<template>
	<view class="Visualization-Page">
		<view class="Visualization-Home">
			<view class="video0">
				<view class="video1">
					<video class="vue3VideoPlay" id="myVideo" :src="vue3VideoPlayUrl" :poster="vue3VideoPlayPoster"
						@error="videoErrorCallback" autoplay loop muted :controls="false">
					</video>
				</view>
			</view>
			<view class="cover2"></view>
			<view class="Visualization_Body">
				<view class="cover"></view>
				<view class="Visualization_header">
					<view class="left0"></view>
					<view class="middle0">
						<view class="middle0_left">
							<view class="middle0_left_row1">大连传染病医院扩建项目综合服务楼</view>
							<view class="middle0_left_row2">
								Dalian Infectious Disease Hospital Expansion Project
							</view>
						</view>
						<view class="middle0_middle">
							<view v-for="(item,index) in tabBars" :class="'visual-middle-' + index">
								<view class="middle0_div">
									<view @click="changeItem(index)" :class="{ choosed: index == currentTabIndex }">
										{{ item.name }}
									</view>
								</view>
							</view>
						</view>
						<div class="middle0_right">
							<div class="right-time ignore-visualization-index-time">
								<div class="shijian ignore-visualization-index-shijian">{{ mrtime ||'8:00:00' }}</div>
								<div class="riqi ignore-visualization-index-shijian">{{ mrdate ||'2023-01-01' }}</div>
							</div>
							<div class="shuxian"></div>
							<div class="right-tem ignore-visualization-index-tem">
								<img :src="'http://portal.xumengte.com/visualization/weather/天气-'+weatherName+'.svg'"
									alt="天气" class="tem-img" @error="setDefaultImage" />
								<img src="http://portal.xumengte.com/homeImg/tem.png" style="height: 15px; width: auto"
									alt="温度" class="tem-img" />
								<div class="tem-num"> {{ mrtem || 27 }}℃</div>
							</div>
							<div class="shuxian"></div>
							<div class="right-pm">
								<div class="pm-top">PM2.5</div>
								<div class="pm-bot">{{ mrpm || 17 }}</div>
							</div>
						</div>
					</view>
					<view class="right0"></view>
				</view>
				<view class="Visualization_bottom">
					<view class="Visualization_content ignore-visualization-content">
						<VisPower v-if="currentChildIndex==1" />
						<Enviroment v-else-if="currentChildIndex==2" />
						<visualione :deviceNum="deviceNum" @changeEvent="handleMyEvent" v-else
							:currentTabIndex="currentChildIndex" @changeTabIndex="changeTabIndexFn"></visualione>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import store from '@/store/index.js';
	import $config from '@/common/config.js';
	import request from '@/common/request.js';
	import VisPower from './components/vispower.vue';
	import Enviroment from './components/enviroment.vue';
	import visualione from './components/visualione.vue';
	// import Hls from "hls.js";
	import {
		VIDEOLIST
	} from "@/common/const_data.js";
	export default {
		components: {
			visualione,
			VisPower,
			Enviroment
		},
		data() {
			return {
				mrtime: '',
				mrdate: '',
				mrtem: '32',
				mrpm: '13',
				weatherName: '晴',
				screenWidth: 960,
				videoContext: {},
				vue3VideoPlayUrl: '/static/dlly/homeVideo.mp4',
				vue3VideoPlayPoster: 'http://portal.xumengte.com/dlly/homeVideo.jpeg',
				deviceNum: 0,
				currentTabIndex: 0,
				currentChildIndex: 0,
				tabBars: [{
						code: 'all',
						name: '综合分析'
					},
					{
						code: 'power',
						name: '能耗分析'
					},
					{
						code: 'env',
						name: '环境分析'
					},
					{
						code: 'cout',
						name: '碳排放'
					},
				],
				videoShow: false,
				connected: false,
				connecting: false,
				socketMsg: false,
				firstFlag: false,
				refreshDecuation: 0, //心跳时间
				refreshDoubleTime: 0, //刷新间隔
				changeTabStatus: false,
				getTimeInterval: '',
				deviceIdArray: []
			}
		},
		onUnload() {
			clearInterval(this.getTimeInterval)
			uni.$off('loginin')
		},
		onLoad() {
			let that = this;
			this.videoShow = true;
			console.log('onLoad==>>');
			this.getTimeInterval = setInterval(this.getTime, 800);
			// plus.screen.lockOrientation('default');
			this.videoContext = uni.createVideoContext('myVideo');
			this.$nextTick(() => {
				that.videoContext.play();
			})
			// this.$refs.videoPlayer.player.play();
			//全局监听按键输入
			uni.getSystemInfo({
				success: function(res) {
					store.commit('setScreenWidth', res.screenWidth);
				}
			})
			// window.document.onkeydown = function(evt) {
			// 	evt = evt || window.event;
			// 	let keyCode = evt.which || evt.keyCode;
			// 	console.log('==keyCode>>', evt.code)
			// 	// document.getElementById("onClick").click();
			// };
			document.addEventListener("keydown", function(event) {
				// 模拟按钮点击后会执行 api 请求，耗时 2 秒
				if (that.changeTabStatus) {
					// 利用 return 终止函数继续运行
					return false;
				}
				// 按下左键
				if (event.key === "ArrowLeft") {
					console.log('==left>>'); // 触发上一页按钮的点击事件
					if (that.currentTabIndex > 0) {
						that.changeItem(that.currentTabIndex - 1);
					}
					console.log('==currentTabIndex>>', that.currentTabIndex);
				}
				// 按下右键
				else if (event.key === "ArrowRight") {
					console.log('==right>>'); // 触发下一页按钮的点击事件
					if (that.currentTabIndex < 3) {
						that.changeItem(that.currentTabIndex + 1);
					}
					console.log('==currentTabIndex>>', that.currentTabIndex);
				}
				that.changeTabStatus = true;
				setTimeout(() => {
					that.changeTabStatus = false;
				}, 2000);
			});
			if (store.state.hasLogin) {
				that.getDeviceNum();
			} else {
				console.log("notLogin===>>>")
				that.loginRequest();
			}
			this.airQualityFn();
			this.weatherLoaderFn();
			uni.$on('loginin', (res) => {
				this.loginRequest();
			});
		},
		onPullDownRefresh() {
			console.log('refresh');
			window.location.reload();
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 2000);
		},
		methods: {
			videoErrorCallback: function() {
				// uni.showModal({
				// 	content: '视频加载失败',
				// 	showCancel: false
				// });
			},
			changeItem(index) {
				let that = this;
				if (this.changeTabStatus) {
					// 利用 return 终止函数继续运行
					return false;
				}
				uni.showLoading({
					mask: true
				})
				this.currentTabIndex = index;
				setTimeout(() => {
					that.currentChildIndex = index;
				}, 200);
				this.changeTabStatus = true;
				setTimeout(() => {
					that.changeTabStatus = false;
					uni.hideLoading()
				}, 2000);
			},
			setDefaultImage(e) {
				e.target.src = 'http://portal.xumengte.com/visualization/weather/天气-晴.svg';
			},
			getTime() {
				let date = new Date()
				let yy = date.getFullYear();
				let mm = date.getMonth() + 1;
				let dd = date.getDate();
				let hh = date.getHours();
				let minutes = date.getMinutes();
				let second = date.getSeconds();
				let mf = minutes < 10 ? '0' + minutes : minutes;
				let ms = second < 10 ? '0' + second : second;
				// nowTimeref.value = hh + ":" + mf + ":" + ms;
				//ms是秒，这里可以根据自己需要调整格式
				this.mrtime = hh + ':' + mf + ':' + ms;
				// nowDateref.value = yy + "年" + mm + "月" + dd + "日";
				this.mrdate = yy + '-' + mm + '-' + dd;
				this.socketMsg = false;
				if (this.refreshDecuation < 5) {
					this.refreshDecuation++
					if (this.refreshDecuation == 1) {
						uni.$emit('reddBotChart');
					} else if (this.refreshDecuation == 3) {
						uni.$emit('refreshBotChart');
					}
				} else {
					this.refreshDecuation = 0
					if (this.refreshDoubleTime < 48) {
						this.refreshDoubleTime++
					} else {
						this.refreshDoubleTime = 0
						this.weatherLoaderFn();
						if (store.state.hasLogin) {
							this.realMData();
						}
					}
				}
				if (this.refreshDecuation % 20 == 0) {
					let index = this.refreshDecuation / 20
					// this.vue3VideoPlayUrl = '/static' + VIDEOLIST[index].url;
				}
			},
			handleMyEvent(data) {
				let that = this;
				if (this.firstFlag) {
					this.$nextTick(() => {
						that.videoShow = false;
						that.videoContext.pause();
					})
					this.vue3VideoPlayUrl = data
					setTimeout(function() {
						that.videoShow = true;
						that.videoContext.play();
					}, 2000);
					// this.vue3VideoPlayPoster = data + '?vframe/jpg/offset/0'
				} else {
					this.firstFlag = true;
				}
			},
			loginRequest() {
				let that = this;
				let postData = {
					"username": "admin",
					"password": "ytsn@jzhq",
					"captcha": "app-skip"
				};
				let headerdata = {
					"content-type": "application/json"
				};
				uni.showLoading({
					mask: true
				})
				request.postRaw('/jeecgboot/sys/login', headerdata, postData).then(resData => {
					console.log('resData==>>', resData);
					if (resData.code == 200) {
						let result = resData.result;

						let projectsArray = resData.result.projects;

						console.log("loginSuccess==>>>", projectsArray.length);

						let projectsInfo = {}

						for (let i = 0; i < projectsArray.length; i++) {
							let projectsDic = projectsArray[i];
							if (projectsDic.code == $config.pcode) {
								Object.keys(projectsDic).forEach((item) => {
									if (projectsDic[item]) {
										projectsInfo[item] = projectsDic[item]
									}
								}); //list为传入的对象值
								store.commit('setProjectsInfo', projectsInfo);
							}
						}

						let loginData = {
							uuid: result.userInfo.id,
							token: result.token,
							projectsInfo: projectsInfo
						}

						console.log("loginData==>>>", loginData);

						store.commit('login', loginData);
						that.getDeviceNum();
					}
				}).catch(errData => {
					uni.hideLoading();
					console.log('errData==env>>', errData)
				});
			},

			realMData() {
				let that = this;
				let postData = {
					deviceIds: this.deviceIdArray.join(','),
				};
				let headerdata = {
					"content-type": "application/json"
				};
				request.postRaw('/jeecgboot/device/data/realData', headerdata, postData).then(resData => {
					console.log('resData==>>', resData);
					if (resData.code == 200) {
						let resultData = resData.result;
						let avgProperties = {
							tvoc: 0,
							temp: 0,
							co2: 0,
							humi: 0,
						}
						let avgConts = {
							tvoc: 0,
							temp: 0,
							co2: 0,
							humi: 0,
						};
						uni.hideLoading()
						console.log('resultData==>>', resultData);
						that.deviceIdArray.forEach((item, index) => {
							// console.log('item==>>', item);
							console.log('resultData.item==>>', resultData[item]);
							let itemObj = JSON.parse(resultData[item]);
							let properties = itemObj.properties;
							for (let key of Object.keys(avgProperties)) {
								if (properties[key] > 0) {
									avgProperties[key] = parseFloat(avgProperties[key]) +
										parseFloat(properties[key])
									avgConts[key]++;
								}
							}
						})
						for (let key of Object.keys(avgProperties)) {
							if (avgConts[key] > 0) {
								avgProperties[key] = (avgProperties[key] / avgConts[
										key])
									.toFixed(2)
							}
						}
						console.log('avgProperties==>>', avgProperties);
						store.commit('setProperties', avgProperties);
						uni.$emit('refreshEnv', avgProperties);
						uni.$emit('refreshTemp', avgProperties);
						uni.$emit('refreshTemps', avgProperties);
						uni.$emit('refreshDevices', avgProperties);
					} else {
						uni.hideLoading()
					}
				}).catch(errData => {
					uni.hideLoading()
					console.log('errData==env>>', errData)
				});
			},
			getDeviceNum() {
				let that = this;
				uni.showLoading({
					mask: true
				})
				request.get('/jeecgboot/project/project/info?projectId=' + $config.pcode).then(resData => {
					console.log('resData==>>', resData);
					if (resData.code == 200) {
						that.deviceNum = resData.result.deviceNum
						uni.$emit('hasdeviceNum');
						that.queryConfigByCode();
					} else {
						uni.hideLoading()
					}
				}).catch(errData => {
					uni.hideLoading()
					console.log('errData296==>>', errData)
					if (errData.code == 401) {
						store.commit('logout');
						that.loginRequest();
					}
				});
			},
			//获取后台项目配置
			queryConfigByCode() {
				let that = this;
				request.get('/jeecgboot/project/project/queryConfigByCode?code=' + $config.pcode).then(resData => {
					if (resData.code == 200) {
						let resultArray = resData.result;
						resultArray.forEach((item, index) => {
							if (item.configCode === 'env') {
								that.deviceIdArray = [];
								let configItems = item.configItems;
								if (configItems && configItems.length > 0) {
									console.log("configItems=>", configItems)
									//此处仅做设备缓存处理(大屏端websocket改善需求)
									configItems.forEach((itm, indx) => {
										that.deviceIdArray[indx] = itm.deviceId.replaceAll("-", "")
											.replaceAll("_", "");
									});
									that.realMData();
									store.commit("setConfigDeviceIds", that.deviceIdArray);
								}
							}
						});
					} else {
						uni.hideLoading()
					}
				}).catch(errData => {
					uni.hideLoading()
					console.log(errData, '-----errData-----')
				})
			},
			airQualityFn() {
				let that = this;
				request.get('/jeecgboot/api/weather/air/now?location=' + $config.locations)
					.then(resData => {
						console.log('resData==>>', resData);
						if (resData.code == 200) {
							let airCity = resData.result.results[0].air.city;
							that.mrpm = airCity.pm25;
						}
					});
			},
			weatherLoaderFn() {
				let that = this;
				request.get('/jeecgboot/api/weather/now?location=' + $config.locations)
					.then(resData => {
						console.log('resData==>>', resData);
						if (resData.code == 200) {
							let nowData = resData.result.results[0].now;
							that.mrtem = nowData.temperature;
							that.weatherName = nowData.text;
						}
					});
			},
			changeTabIndexFn(i) {
				// console.log(i, '-----i-----')
				// this.changeItem(i)
				this.currentTabIndex = i;
				if (i == 0) {
					this.currentChildIndex = -1;
				}
			}

		}
	}
</script>

<style scoped>
	@import 'visualization.css';
</style>
